package com.tien.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.rowset.spi.XmlWriter;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sun.rowset.WebRowSetImpl;
import com.sun.rowset.internal.WebRowSetXmlWriter;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.SyndFeedOutput;
import com.sun.syndication.io.XmlReader;
import com.tien.model.rss.LemonFeed;
import com.tien.model.rss.LemonFeedItem;
import com.tien.service.TestService;
import com.tien.utils.AbstractAction;
import com.tien.utils.ConstantsTool;
import com.tien.utils.DateFomatTool;

/**
 * @author Tien E-mail:g.tianxin@gmail.com
 * @version Time：2011-6-9 下午11:12:54
 */
@Controller
@Scope("prototype")
public class RSSReaderAction extends AbstractAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7102228867847561243L;
	@Autowired
	private TestService testService;

	private String rssUrl;

	private static List<LemonFeed> lemonFeedList;

	private String rssFeedId;
	private String rssFeedName;
	private String rssFeedLink;
	private String rssFeedDesc;

	private String rssEntryName;
	private String rssEntryLink;
	private String rssEntryDesc;

	private String status;
	private Map<String, String> params = new HashMap<String, String>();

	@Override
	public String execute() {
		rssUrl = "http://127.0.0.1/lemon/rss-xml/"
				+ DateFomatTool
						.getNewDateStringOfFomat(ConstantsTool.RSS_DATE_FORMAT)
				+ ".xml";
		getSyndFeed();
		// lemonFeed = new LemonFeed();
		// lemonFeed.setTitle("lemon tree");
		// lemonFeed.setFeedType("RSS_2.0");
		// lemonFeed.setLink("http://www.openfire.tk/lemon");
		// List<LemonFeedItem> lemonFeedItem = new ArrayList<LemonFeedItem>();
		// lemonFeedItem.add(new LemonFeedItem("title", "String link",
		// "String description"));
		// lemonFeedItem.add(new LemonFeedItem("title", "String link",
		// "String description"));
		// lemonFeedItem.add(new LemonFeedItem("title", "String link",
		// "String description"));
		// lemonFeedMap.put(lemonFeed, lemonFeedItem);
		return SUCCESS;
	}

	public void getRSSXML() {
		URL feedUrl = null;
		InputStream is = null;
		InputStreamReader inputStreamReader;
		StringBuffer stringBuffer = new StringBuffer();
		PrintWriter out = null;
		try {
			feedUrl = new URL(rssUrl);
			is = feedUrl.openStream();
			inputStreamReader = new InputStreamReader(is, "UTF-8");
			BufferedReader br = new BufferedReader(inputStreamReader);
			String s = "";
			while ((s = br.readLine()) != null) {
				stringBuffer.append(s);
			}
			response.setContentType("text/xml;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			out = response.getWriter();
			out.write(stringBuffer.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException ioe) {
			}
		}

		try {
			new XmlReader(feedUrl).toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void createRSSLocalXmlFile() {
		SyndFeedImpl syndFeedImpl = getSyndFeed();
		outputLocalXMLFile(syndFeedImpl);
	}

	private SyndFeedImpl getSyndFeed() {
		URL feedUrl = null;
		try {
			feedUrl = new URL(rssUrl);
		} catch (MalformedURLException e1) {
			return null;
		}
		SyndFeedInput input = new SyndFeedInput();
		SyndFeed xmlFeeds = null;
		try {
			xmlFeeds = input.build(new XmlReader(feedUrl));
		} catch (Exception e) {
		}
		return (SyndFeedImpl) xmlFeeds;
	}

	private void outputLocalXMLFile(SyndFeed feed) {
		if (feed == null) {
			status = "The feed name is exist, please check the input feed name!";
			try {
				response.getWriter().println(status);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
		String fileName = request.getRealPath("")
				+ "/rss-xml/"
				+ DateFomatTool
						.getNewDateStringOfFomat(ConstantsTool.RSS_DATE_FORMAT)
				+ ".xml";
		System.out.println(fileName);
		Writer writer;
		try {
			writer = new FileWriter(fileName);
			SyndFeedOutput output = new SyndFeedOutput();
			output.output(feed, writer);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FeedException e) {
			e.printStackTrace();
		}
	}

	public String appIframe() {
		return "appIframe";
	}

	public String createFeedRSSFile() throws UnsupportedEncodingException {
		rssFeedLink = request.getScheme() + "://" + request.getServerName()
				+ request.getContextPath() + "/rss-xml/" + rssFeedName + ".xml";
		// rssFeedLink = "http://127.0.0.1/lemon/rss-xml/" + rssFeedName +
		// ".xml";
		SyndFeed feed = new SyndFeedImpl();
		feed.setFeedType("rss_2.0");
		feed.setTitle(rssFeedName);
		feed.setLink(rssFeedLink);
		feed.setDescription(rssFeedDesc);
		String fileName = request.getRealPath("") + "/rss-xml/"
				+ rssFeedName + ".xml";
		System.out.println(fileName);
		Writer writer;
		try {
			SyndFeedOutput output = new SyndFeedOutput();
			writer = new OutputStreamWriter(new FileOutputStream(fileName),
					"UTF-8");
			output.output(feed, writer);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		LemonFeed lemonFeed = new LemonFeed();
		lemonFeed.setFeedType("rss_2.0");
		lemonFeed.setTitle(rssFeedName);
		lemonFeed.setLink(rssFeedLink);
		lemonFeed.setDescription(rssFeedDesc);
		lemonFeedList.add(lemonFeed);
		addRSSFeed();
		return "rssFeedList";
	}

	private void addRSSFeed() {
		params.put("feedType", "rss_2.0");
		params.put("title", rssFeedName);
		params.put("link", rssFeedLink);
		params.put("description", rssFeedDesc);
		params.put("userId", "1");
		testService.saveLemonFeed(params);
	}

	public String getRSSFeed() {
		lemonFeedList = testService.getLemonFeedList("1");
		return "rssFeedList";
	}

	public void deleteRSSFeed() {
		File file = new File(rssUrl);
		boolean isExists = file.exists();
		if(isExists){
			file.delete();
		}
		testService.deleteLemonFeed(Integer.parseInt(rssFeedId));
		try {
			JSONObject jsonObject = new JSONObject();
			Map<String, String> json = new HashMap<String, String>();
			json.put("status", "S");
			jsonObject.putAll(json);
			response.getWriter().println(jsonObject);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Map<String, String> getParams() {
		return params;
	}

	public void setParams(Map<String, String> params) {
		this.params = params;
	}

	public String getRssUrl() {
		return rssUrl;
	}

	public void setRssUrl(String rssUrl) {
		this.rssUrl = rssUrl;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getRssFeedName() {
		return rssFeedName;
	}

	public void setRssFeedName(String rssFeedName) {
		this.rssFeedName = rssFeedName;
	}

	public String getRssFeedDesc() {
		return rssFeedDesc;
	}

	public void setRssFeedDesc(String rssFeedDesc) {
		this.rssFeedDesc = rssFeedDesc;
	}

	public String getRssEntryName() {
		return rssEntryName;
	}

	public void setRssEntryName(String rssEntryName) {
		this.rssEntryName = rssEntryName;
	}

	public String getRssEntryLink() {
		return rssEntryLink;
	}

	public void setRssEntryLink(String rssEntryLink) {
		this.rssEntryLink = rssEntryLink;
	}

	public String getRssEntryDesc() {
		return rssEntryDesc;
	}

	public void setRssEntryDesc(String rssEntryDesc) {
		this.rssEntryDesc = rssEntryDesc;
	}

	public String getRssFeedLink() {
		return rssFeedLink;
	}

	public void setRssFeedLink(String rssFeedLink) {
		this.rssFeedLink = rssFeedLink;
	}

	public List<LemonFeed> getLemonFeedList() {
		return lemonFeedList;
	}

	public void setLemonFeedList(List<LemonFeed> lemonFeedList) {
		this.lemonFeedList = lemonFeedList;
	}

	public String getRssFeedId() {
		return rssFeedId;
	}

	public void setRssFeedId(String rssFeedId) {
		this.rssFeedId = rssFeedId;
	}

}
